<?php
/**
 * GeoContexter
 * @link http://code.google.com/p/geocontexter/
 * @package GeoContexter
 */

/**
 * spatial search for record items
 *
 * @package GeoContexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev: 153 $ / $LastChangedDate: 2010-02-18 17:21:41 +0100 (jeu., 18 févr. 2010) $ / $LastChangedBy: armand.turpel $
 */

namespace Gospecies\Controller;

use Zend\View\Model\ViewModel;
use Gospecies\Controller\AbstractIdentityJsonController;
use Zend\View\Model\JsonModel;

class AjaxSearchRecordJson2Controller extends AbstractIdentityJsonController
{
    /**
     */
    public function indexAction()
    {
        // get logged user
        $this->user = $this->get_identity();

        $params = array();

        // check permission if id_group is "contributor" or above.
        // users of those groups can only update own projects
        //
        if ((isset($this->user->id_group) && ((int)$this->user->id_status == 200))) {
            if (((int)$this->user->id_group >= 300) && ((int)$this->user->id_group < 500)){
              $params['id_owner'] = $this->user->id_user;
            } elseif ((int)$this->user->id_group >= 500){
              return new JsonModel(array('error' => 'permission denied'));
            }
        } else {
            return new JsonModel(array('error' => 'permission denied'));
        }

        $params['geometry_column'] = 'point';

        if ($this->request->getPost()->geom !== null) {
            $params['geom'] = $this->build_geometry(trim((string) $this->request->getPost()->geom));

        }

        if ($this->request->getPost()->id_project !== null) {
            $params['id_project'] = $this->request->getPost()->id_project;
        }

        if ($this->request->getPost()->page !== null) {
            $params['page'] = trim($this->request->getPost()->page);
        }

        if ($this->request->getPost()->limit !== null) {
            $itemCountPerPage = (int)trim($this->request->getPost()->limit);
        } else {
          $itemCountPerPage = 10;
        }

        if ($this->request->getPost()->buffer !== null) {
            $params['buffer'] = trim($this->request->getPost()->buffer);
        }

        if ($this->request->getPost()->date_from !== null) {
            $params['date_from'] = trim($this->request->getPost()->date_from);
        }

        if ($this->request->getPost()->date_to !== null) {
            $params['date_to'] = trim($this->request->getPost()->date_to);
        }

        if ($this->request->getPost()->alpha_filter !== null) {
            $params['alpha_filter'] = trim($this->request->getPost()->alpha_filter);
        }

        if (($id_keyword = $this->request->getPost()->id_keyword) !== null) {
          if (is_array($id_keyword) && (count($id_keyword) > 0)) {
              $params['in_item_list_id_keyword']  = $id_keyword;
          }
        }

        $params['default_display'] = true;


        $in_id_list       = array();

        // set offset for sql limit clause
        //
        if (isset($params['page']) && (('' == $params['page']) || (1 == (int)$params['page']))) {
            $offset = 0;
            $page   = 1;
        } else {
            $offset = ((int)$params['page'] - 1) * $itemCountPerPage;
        }

        $params['limit']                   = array($itemCountPerPage,$offset);
        $params['no_transform_attributes'] = false;
        //$params['status']                = array('=', 1000);
        $params['order']                   = 'id_record DESC';

        try {

          $RecordSearch = $this->CoreModel('RecordSearch');


          $result  = $RecordSearch->run( $params );

          if ($result instanceof \Core\Library\Exception) {
              return new JsonModel(array('error' => $result->getMessage()));

          }

          foreach ($result as & $__record) {

              $item = $this->itemDetails( $__record['id_item'] );

              $__record['item'] = array('key'   => 'Taxon',
                                        'value' => $item['title']);

              $__record['item_attribute'] = array('key'   => 'Taxon',
                                                  'value' => $item['attributes']);

                 $RecordMediaGetAll = $this->CoreModel('RecordMediaGetAll');

        $params  = array('id_record' => $__record['id_record'],
                         'id_type'   => 1);

        $media = $RecordMediaGetAll->run( $params );

        if ($media instanceof \Core\Library\Exception) {

          return $this->error( $media->getMessage(), __file__, __line__);

        } else {

           if (isset($media[0])) {

             foreach($media as &$m) {

                  $_tmp = json_decode($m['media']);

                  $_tmp->media_folder_hash = $__record['media_folder_hash'];

                $m['media'] = $_tmp;
             }

           }

           $__record['image'] = $media;

        }
          }
//die(var_export($result,true));
          return new JsonModel($result);

          } catch (\Exception $e) {

            $this->default_error = "Error\n File: " . __file__ . "\nLine: " . __line__ . "\nError: " . $e->getMessage();

            return new JsonModel(array('error' => $this->default_error));

          }

    }

    private function itemDetails( $id_item )
    {
        $ItemGet = $this->CoreModel('ItemGet');

        $params  = array('id_item' => $id_item);

        $result  = $ItemGet->run( $params );

        return $result;

    }

    private function build_geometry($geom)
    {
        return "ST_GeometryFromText('{$geom}',4326)";
    }
}

